package com.rtx.config.datasource;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.BeansException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.rtx.api.utils.MultipleDataSource;

@Configuration
public class DatasourceConfig implements ApplicationContextAware{
	
    @Bean("enterprise")
    @ConfigurationProperties(prefix = "spring.datasource100")
    public DataSource dataSource100() {
    	return DataSourceBuilder.create().build();
    }
    
    @Bean("wmwhse1")
    @ConfigurationProperties(prefix = "spring.datasource1")
    public DataSource dataSource1() {
    	return DataSourceBuilder.create().build();
    }

    
    @Bean("ris_edi")
    @ConfigurationProperties(prefix = "spring.datasource0")
    public DataSource dataSourcedefault() {
    	return DataSourceBuilder.create().build();
    }
    
    @Primary
    @Bean
    public DataSource primaryataSource() {
        try {
			return setMultipleDataSource();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
        return null;
    }
    
    ApplicationContext context;
    

    /**
     * 配置多数据源
     * @return
     * @throws IOException
     * @throws SQLException
     */
    public MultipleDataSource setMultipleDataSource() throws IOException, SQLException {
    	MultipleDataSource dataSource=new MultipleDataSource();
    	Map<Object,Object> map=new HashMap<>();
    	
    	dataSource.setDefaultTargetDataSource(dataSourcedefault());
    	String[] names = context.getBeanNamesForType(DataSource.class);
    	for(String datasourcekey:names) {
    		if("ris_edi".equals(datasourcekey)||"primaryataSource".equals(datasourcekey)) {
    			continue;
    		}
    		System.out.println("***********************************************************");
        	System.out.println("加载数据源===="+datasourcekey);
        	System.out.println("***********************************************************");
    		map.put(datasourcekey, context.getBean(datasourcekey));
    	}
    	
    	dataSource.setTargetDataSources(map);
    	return dataSource;
    }
    

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		context = applicationContext;
		
	}
}
